package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category, HttpServletRequest request) {
        // 非空判断
        if (category.getName() == null || category.getSort() == null ||
                category.getType() == null) {
            return R.error("请求参数错误");
        }
        // 分类类型 只能为 1 菜品分类 2 套餐分类
        if (!(category.getType() == 1 || category.getType() == 2)) {
            return R.error("请求参数错误");
        }
        // 分类名称不能重复
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.select(Category::getName);
        List<Category> categoryList = categoryService.list(lqw);
        for (Category category1 : categoryList) {
            if (category.getName().equals(category1.getName())) {
                return R.error("分类名称不能重复");
            }
        }
        log.info("category:{}", category);
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        Long empId = Long.valueOf((String) request.getSession().getAttribute("employeeId"));
//        category.setCreateUser(empId);
//        category.setUpdateUser(empId);
        category.setIsDeleted(0);
        boolean saveFlag = categoryService.save(category);
        if (!saveFlag) {
            return R.error("添加分类失败");
        }
        return R.success("添加分类成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
        log.info("page = {},pageSize = {}", page, pageSize);
        if (page == null || pageSize == null || page <= 0 || pageSize <= 0) {
            return R.error("请求参数有误");
        }
        Page<Category> pageInfo = categoryService.page(new Page<>(page, pageSize));
        if (pageInfo == null) {
            R.error("没有查到分类信息");
        }
        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        log.info("删除分类，id为：{}", id);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishLambdaQueryWrapper);
        if (dishCount >= 1) {
            return R.error("分类与菜品表关联, 不能删除");
        }
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        if (setmealCount >= 1) {
            return R.error("分类与套餐表关联, 不能删除");
        }
        boolean deleteFlag = categoryService.removeById(id);
        if (!deleteFlag) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    /**
     * 根据id修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        if (category == null || category.getId() == null) {
            return R.error("请求参数有误");
        }
        boolean updateFlag = categoryService.updateById(category);
        if (!updateFlag) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    /**
     * 备用
     * 新增菜品时, 返回菜品分类给表单
     *
     * @param type
     * @return
     */
    @GetMapping("/list2")
    public R<List<Category>> queryByType(@RequestParam Integer type) {
        log.info("请求的类型 (1菜品分类 2套餐分类)：{}", type);
        if (type == null || !(type == 1 || type == 2)) {
            return R.error("请求参数错误");
        }
        LambdaQueryWrapper<Category> categoryLQW = new LambdaQueryWrapper<>();
        categoryLQW.eq(Category::getType, type);
        List<Category> list = categoryService.list(categoryLQW);
        return R.success(list);
    }

    /**
     * 根据条件查询分类数据
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        log.info("category : {}", category);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // category.getType() != null 条件存在
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getType);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
